package com.ynny.Service.Impl;

import com.ynny.Dao.HobbyDao;
import com.ynny.Entity.Hobby;
import com.ynny.Entity.R;
import com.ynny.Dao.UsersDao;
import com.ynny.Entity.Users;
import com.ynny.Entity.UsersDTO;
import com.ynny.Service.HobbyService;
import com.ynny.Service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private UsersDao usersDao;
    @Autowired
    private HobbyDao hobbyDao;
    @Autowired
    private HobbyService hobbyService;

    @Override
    @Transactional
    public R login(Users users) {
        try {
//                    检查用户是否存在
            Users users1 = usersDao.findUserByName(users.getNumber());
            if(users1 == null){
                System.out.println("用户不存在！");
                return R.error("用户不存在！");//用户不存在
            }else if(!users1.getPassword().equals(users.getPassword())){
                System.out.println("密码错误！");
                return R.error("密码错误！");//密码错误
            }else {
                System.out.println(users1.getIdentity()+"用户登录成功！");
                return R.ok(users);//登录成功
            }
        }catch (Exception e){
            System.out.println("用户登录失败！");
            return R.error("服务器出现异常！");
        }
    }

    @Override
    @Transactional
    public int addUserTable(String number, String password, String identity,String sex) {
        //查询有无该用户
        Users users = usersDao.findUserByName(number);
        Users newUsers = new Users();
        if(users == null){
            newUsers.setNumber(number);
            newUsers.setPassword(password);
            newUsers.setIdentity(identity);
            newUsers.setSex(sex);
        }            //添加用户，到用到用户表

        return usersDao.addUser(newUsers);//添加到数据库return i1;
    }


    @Override
    @Transactional  // 关键事务注解
    public R registerUserWithHobbies(UsersDTO usersDTO) {
        Users users = usersDTO.getUsers();
        List<Hobby> hobbies = usersDTO.getHobbies();
        // 参数校验
        if (users == null || hobbies == null || hobbies.isEmpty()) {
            throw new IllegalArgumentException("参数不合法");
        }

        // 检查用户编号唯一性
        if (usersDao.existsByNumber(users.getNumber())) {
            return R.error("用户编号已存在");
        }

        // 插入用户
        int userInserted = usersDao.addUser(users);
        if (userInserted <= 0) {
            throw new RuntimeException("用户信息插入失败");// 触发事务回滚
        }

        // 插入爱好（已修复事务回滚逻辑）
        hobbyService.addHobbyTable(users.getNumber(), hobbies);

        return R.ok(users.getNumber());
    }

}
